package com.jh.tools.common.file;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.text.TextUtils;

import com.apkfuns.logutils.LogUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class FILE {
	private static FILE mFILE;
	public static FILE getInstance(){
		return mFILE==null?mFILE=new FILE():mFILE;
	}

	/**
	 * 获取拼接文件名
	 * @param postfix
	 * @return
	 */
    public String getfileName(String postfix){
			return postfix.contains(".")?UUID.randomUUID().toString() + postfix:null;
	}
	/**
	 * 改变文件权限
	 * 
	 * @param permission
	 * @param filePathName
	 */
	public  void chmod(String permission, String filePathName) {
		try {
			String command = "chmod " + permission + " " + filePathName;
			Runtime runtime = Runtime.getRuntime();
			runtime.exec(command);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 重命名
	 * 
	 * @param filePathName
	 * @param newPathName
	 */
	public  boolean rename(String filePathName, String newPathName) {
		if (TextUtils.isEmpty(filePathName))
			return false;
		if (TextUtils.isEmpty(newPathName))
			return false;
		FILE.getInstance().delete(newPathName); // 新名称对应的文件可能已经存在，先删除
		File file = new File(filePathName);
		File newFile = new File(newPathName);
		return file.renameTo(newFile);
	}

	/**
	 * 复制文件
	 * 
	 * @param from
	 * @param toPathName
	 * @return
	 */
	public  int copy(InputStream from, String toPathName) {
		try {
			FILE.getInstance().delete(toPathName);
			OutputStream to = new FileOutputStream(toPathName);
			byte buf[] = new byte[1024];
			int c;
			while ((c = from.read(buf)) > 0) {
				to.write(buf, 0, c);
			}
			from.close();
			to.close();
			return 0;
		} catch (Exception ex) {
			ex.printStackTrace();
			return -1;
		}
	}

	/**
	 * 删除文件
	 */
	public  void delete(String filePathName) {
		if (TextUtils.isEmpty(filePathName))
			return;
		File file = new File(filePathName);
		if (file.isFile() && file.exists()) {
			file.delete();
		}
	}

	/**
	 * 创建目录，整个路径上的目录都会创建
	 * 
	 * @param path
	 */
	public  void createDir(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	public  void deleteDirectory(File file) {
		if (!file.isDirectory()) {
			return;
		}
		File[] paths = file.listFiles();
		for (File pathF : paths) {
			if (pathF.isDirectory()) {
				deleteDirectory(pathF);
			} else {
				pathF.delete();
			}
		}
		file.delete();
	}

	/**
	 * 获取目录的名称 注意：只能获取如：/aaaa/ssss/ 或 /aaaa/dsddd
	 * 
	 * @param filePathName
	 * @return
	 */
	public  String getDirPathName(String filePathName) {
		try {
			if (filePathName.endsWith("/"))
				filePathName = filePathName.substring(0,
						filePathName.lastIndexOf('/'));
			return filePathName.substring(filePathName.lastIndexOf("/") + 1,
					filePathName.length());
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 文件是否存在
	 * 
	 * @param filePathName
	 * @return
	 */
	public  boolean isExist(String filePathName) {
		if (TextUtils.isEmpty(filePathName))
			return false;
		File file = new File(filePathName);
		return (!file.isDirectory() && file.exists());
	}

	public  boolean isDirExist(String filePathName) {
		if (!filePathName.endsWith("/"))
			filePathName += "/";
		File file = new File(filePathName);
		return (file.isDirectory() && file.exists());
	}

	/**
	 * 获取路径，不带文件名，末尾带'/'
	 * 
	 * @param filePathName
	 * @return
	 */
	public  String getPath(String filePathName) {
		try {
			return filePathName.substring(0, filePathName.lastIndexOf('/') + 1);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 获取文件名，带后缀
	 * 
	 * @param filePathName
	 * @return
	 */
	public  String getName(String filePathName) {
		try {
			return filePathName.substring(filePathName.lastIndexOf('/') + 1);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 获取文件名，不带后缀
	 * 
	 * @return
	 */
	public  String getNameNoPostfix(String filePathName) {
		try {
			return filePathName.substring(filePathName.lastIndexOf('/') + 1,
					filePathName.lastIndexOf('.'));
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 获取文件类型
	 * 
	 * @param fileName
	 *            (文件名不带路径)
	 * @return
	 */
	public  String getFileType(String fileName) {
		if (TextUtils.isEmpty(fileName))
			return "";
		int index = 0;
		if ((index = fileName.lastIndexOf(".")) > 0) {
			return fileName.substring(index + 1, fileName.length());
		}
		return "";
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @param filePathName
	 * @return
	 */
	public  String getExtension(String filePathName) {
		if (filePathName == null)
			return null;
		final int index = filePathName.lastIndexOf('.');
		return (index != -1) ? filePathName.substring(index + 1).toLowerCase()
				.intern() : "";
	}

	/**
	 * @param url 要下载的文件地址
	 * @return Bitmap对象
	 */
	public  Bitmap DownloadImageFromNet(String url) {
		Bitmap bt = null;
		try {
            /*
             * *************** 取得的是byte数组, 从byte数组生成bitmap***********************
             * byte[] data =
             * getImage(filePath); if(data!=null){ bitmap =
             * BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
             * imageView.setImageBitmap(bitmap);// display image }else{
             * Toast.makeText(AndroidTest2_3_3.this, "Image error!", 1).show();
             * }
             */
			// ******** 取得的是InputStream，直接从InputStream生成bitmap ***********/
			bt = BitmapFactory.decodeStream(getImageStream(url));
			if (bt != null) {
				return bt;
			}
		} catch (Exception e) {
			// Toast.makeText(context, "Newwork error!",
			// Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 构建输入流
	 *
	 * @param path
	 *            The path of image
	 * @return InputStream
	 * @throws Exception
	 */
	public  InputStream getImageStream(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod("GET");
		conn.connect();
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			return conn.getInputStream();
		}
		return null;
	}

	/**
	 * 把下载的图片保存到本地，如果已经存在同名的文件，则覆盖。保存的类型是JPEG
	 *
	 * @param bm Bitmap实例
	 * @param fileName
	 *            指定图片的名字
	 * @param savePath
	 *            要把图片保存到的路径
	 * @throws IOException
	 */
	public  void saveFile(Bitmap bm, String fileName, String savePath)
			throws IOException {
		if (bm != null) {
			String SAVE_PATH = savePath;
			File dirFile = new File(SAVE_PATH);
			if (!dirFile.exists()) {
				dirFile.mkdir();
			}
			File myCaptureFile = new File(SAVE_PATH + fileName);
			if (myCaptureFile != null) {  //如果已经存在同名的文件，则覆盖
				myCaptureFile.delete();
			}
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(myCaptureFile));
			bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
			bos.flush();
			bos.close();
		}
	}
	public  String readFromFile(Context context){


		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

			String foldername = Environment.getExternalStorageDirectory().getPath()+ "/chumo/IMEI";
			File folder = new File(foldername);

			if (folder == null || !folder.exists()) {
				folder.mkdirs();
			}

			File targetFile=new File("/sdcard/chumo/IMEI/chumo.txt");
			String readedStr="";

			try{
				if(!targetFile.exists()){
					targetFile.createNewFile();
					return null;
				}else{
					InputStream in = new BufferedInputStream(new FileInputStream(targetFile));
					BufferedReader br= new BufferedReader(new InputStreamReader(in, "UTF-8"));
					String tmp;

					while((tmp=br.readLine())!=null){
						readedStr+=tmp;
					}
					br.close();
					in.close();

					return readedStr;
				}
			} catch (Exception e) {
				LogUtils.e(e.getMessage());
//				Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
				return null;
			}
		}else{
			LogUtils.e("未发现SD卡！");
			return null;
		}

	}
	public  void savedToText(Context context,String stringToWrite){

		if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {

			String foldername = Environment.getExternalStorageDirectory().getPath()+ "/chumo/IMEI";
			File folder = new File(foldername);

			if (folder == null || !folder.exists()) {
				folder.mkdir();
			}

			String fileName="/chumo"+".txt";

			File targetFile = new File(foldername + fileName);
			OutputStreamWriter osw;

			try{
				if(!targetFile.exists()){
					targetFile.createNewFile();
					osw = new OutputStreamWriter(new FileOutputStream(targetFile),"utf-8");
					osw.write(stringToWrite);
					osw.close();
				}else{
					osw = new OutputStreamWriter(new FileOutputStream(targetFile,true),"utf-8");
					osw.write("\n"+stringToWrite);
					osw.flush();
					osw.close();
				}
			} catch (Exception e) {
				LogUtils.e(e.getMessage());
//				Toast.makeText(context,e.toString(),Toast.LENGTH_LONG).show();
			}
		}else{
			LogUtils.e("未发现SD卡！");
//			Toast.makeText(context,"未发现SD卡！",Toast.LENGTH_LONG).show();
		}
	}
}